package com.etogc.groupchat.mine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.etogc.dialog.CommonDialog;
import com.etogc.dialog.UpdateNameDialog;
import com.etogc.groupchat.R;
import com.etogc.groupchat.bean.MessageEvent;
import com.etogc.groupchat.bean.UpdatePhotoBean;
import com.etogc.groupchat.common.WebActivity;
import com.etogc.groupchat.group.ui.FavGroupActivity;
import com.etogc.groupchat.group.ui.JoinGroupActivity;
import com.etogc.groupchat.group.ui.MyGroupActivity;
import com.etogc.groupchat.login.ui.ForgetActivity;
import com.etogc.groupchat.login.ui.RegActivity;
import com.etogc.groupchat.main.MainActivity;
import com.etogc.groupchat.common.CommonSp;
import com.etogc.util.GcUrl;
import com.etogc.util.ImageUtils;
import com.etogc.util.IntentHelper;
import com.etogc.util.photo.Bimp;
import com.etogc.util.photo.PhotoActivity;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * Created by AMing on 16/6/21.
 * Company RongCloud
 */
public class MineFragment extends Fragment implements View.OnClickListener {
    private static final int COMPARE_VERSION = 54;
    public static final String SHOW_RED = "SHOW_RED";
    private SharedPreferences sp;
    private ImageView rivHeader;
    private TextView mName;
    private TextView tvMineId;
    private TextView tvSetPwd;
    private ImageView mNewVersionView;
    private boolean isHasNewVersion;
    private String url;
    private boolean isDebug;
    LinearLayout llMyGroup;
    private AsyncTask asyncTask;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.mine_fragment, container, false);
        isDebug = getContext().getSharedPreferences("config", getContext().MODE_PRIVATE).getBoolean("isDebug", false);
        initViews(mView);
        initData();
        EventBus.getDefault().register(this);
        return mView;
    }

    private void initData() {
        sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
        updateUserInfo();
        mName.setText("昵称:" + CommonSp.getNickName());
        tvMineId.setText("831号:" + CommonSp.getUserID());
        String headUrl = CommonSp.getHeadUrl();
        ImageUtils.setRadiuImage(getActivity(), headUrl, rivHeader);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessage().equals("UPDATE_NAME")) {
            String nickName = CommonSp.getNickName();
            mName.setText("昵称:" + nickName);
        }
    }

    private void initViews(View mView) {
        rivHeader = mView.findViewById(R.id.rivHeader);
        mName = mView.findViewById(R.id.mine_name);
        tvMineId = mView.findViewById(R.id.tv_mine_id);
        LinearLayout mUserProfile = mView.findViewById(R.id.start_user_profile);
        LinearLayout mMineService = mView.findViewById(R.id.mine_service);
        LinearLayout mMineAbout = mView.findViewById(R.id.mine_about);
        View bindSocial = mView.findViewById(R.id.llBindSocial);
        View setPwd = mView.findViewById(R.id.llSetPwd);
        String loginType = CommonSp.getLoginType();
        if (loginType.equals("wx")) {
            setPwd.setVisibility(View.GONE);
            bindSocial.setVisibility(View.VISIBLE);
        } else {
            setPwd.setVisibility(View.VISIBLE);
            bindSocial.setVisibility(View.GONE);
        }
        setPwd.setOnClickListener(this);
        bindSocial.setOnClickListener(this);
        mUserProfile.setOnClickListener(this);
        mMineService.setOnClickListener(this);
        mMineAbout.setOnClickListener(this);
        mView.findViewById(R.id.llMore).setOnClickListener(this);
        rivHeader.setOnClickListener(this);
        mView.findViewById(R.id.llJoinGroup).setOnClickListener(this);
        mView.findViewById(R.id.my_wallet).setOnClickListener(this);
        mView.findViewById(R.id.llPrivate).setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llPrivate:
                jumpWeb();
                break;
            case R.id.llMore:
                IntentHelper.jump(getActivity(), SettingActivity.class);
                break;
            case R.id.llBindSocial:
                IntentHelper.jump(getActivity(), RegActivity.class, "type", "bind");
                break;
            case R.id.llSetPwd:
                IntentHelper.jump(getActivity(), ForgetActivity.class);
                break;
            case R.id.rivHeader:
                startActivity(new Intent(getActivity(), MainActivity.class));
                Intent intent = new Intent(getActivity(), PhotoActivity.class);
                startActivityForResult(intent, 5);
                break;
            case R.id.start_user_profile:
                new UpdateNameDialog(getActivity()).initDialog().show();
                break;
            case R.id.mine_service:
                jumpMyGroup();
//                CSCustomServiceInfo.Builder builder = new CSCustomServiceInfo.Builder();
//                builder.province("北京");
//                builder.city("北京");
//                RongIM.getInstance().startCustomerServiceChat(getActivity(), "KEFU146001495753714", "在线客服", builder.build());
                // KEFU146001495753714 正式  KEFU145930951497220 测试  小能: zf_1000_1481459114694   zf_1000_1480591492399
                break;
            case R.id.mine_about:
                final CommonDialog commonDialog = new CommonDialog(getActivity(), "退出", "是否确认退出登录");
                commonDialog.initDialog().show();
                commonDialog.setOnOkClickListener(new CommonDialog.onOkClickListener() {
                    @Override
                    public void onSure() {
                        clear();
                        getActivity().finish();
                        commonDialog.dismiss();
                    }
                });

                break;
            case R.id.my_wallet:
                jumpFavGroup();
                break;
            case R.id.llJoinGroup:
                jumpJoinGroup();
                break;
        }
    }

    private void jumpWeb() {
        String url = GcUrl.HOST + "/static/privacy.html";
        Intent intent = new Intent(getActivity(), WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", "隐私政策");
        startActivity(intent);
    }

    private void clear() {
        CommonSp.setNickName("");
        CommonSp.setToken("");
        CommonSp.setRongToken("");
        CommonSp.setHeadUrl("");
    }


    private void jumpFavGroup() {
        IntentHelper.jump(getActivity(), FavGroupActivity.class);
    }

    private void jumpJoinGroup() {
        IntentHelper.jump(getActivity(), JoinGroupActivity.class);
    }

    private void jumpMyGroup() {
        IntentHelper.jump(getActivity(), MyGroupActivity.class);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void updateUserInfo() {
//        String userId = sp.getString(SealConst.SEALTALK_LOGIN_ID, "");
//        String username = sp.getString(SealConst.SEALTALK_LOGIN_NAME, "");
//        String userPortrait = sp.getString(SealConst.SEALTALK_LOGING_PORTRAIT, "");
//        mName.setText(username);
//        if (!TextUtils.isEmpty(userId)) {
//            String portraitUri = SealUserInfoManager.getInstance().getPortraitUri
//                    (new UserInfoBean(userId, username, Uri.parse(userPortrait)));
//            ImageLoader.getInstance().displayImage(portraitUri, rivHeader, App.getOptions());
//        }
    }

    private String photoPath = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /* 拍照返回的图片 */
        if (requestCode == 5 && resultCode == 99) {
            if (data != null) {
                photoPath = data.getStringExtra("photoPath");
                setHeadImageAfterUpload();
            }
        }
    }


    private String imgUrl = "";

    private String saveBitmap(Bitmap bitmap) {
        String path = Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + ".jpg";
        Log.e("MineFragment", "path=" + path);
        File file = new File(path);
//        File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 上传头像后，不去网络下载，而是直接使用本地地址，设置圆形头像
     */
    @SuppressLint("StaticFieldLeak")
    private void setHeadImageAfterUpload() {
        if (photoPath != null && photoPath.equals("")) {
            return;
        }
        Bitmap bitmap;
        if (photoPath != null) {
            bitmap = Bimp.Compression(photoPath, 240, 240);
            rivHeader.setImageBitmap(bitmap);
//            byte[] bb = Bimp.getImageBytes(bitmap);
//            UploadImageUtil.uploadAvatarByMultipart(bb);
            String path = saveBitmap(bitmap);
            new AsyncTask() {
                @Override
                protected Object doInBackground(Object[] params) {
                    String response = UploadImageUtil.uploadFile(new File(String.valueOf(params[0])), GcUrl.UPLOAD_HEAD);
                    return response;
                }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    Log.e("MineFragment", "开始上传");
                }

                @Override
                protected void onPostExecute(Object o) {
                    super.onPostExecute(o);
                    if (o != null) {
                        String s = o.toString();
                        UpdatePhotoBean updatePhotoBean = new Gson().fromJson(s, UpdatePhotoBean.class);
                        if (updatePhotoBean.getResultCode() == 200) {
                            String userID = CommonSp.getUserID();
                            String nickName = CommonSp.getNickName();
                            String photo = ImageUtils.getImageUrl(updatePhotoBean.getData().getPhoto());
                            CommonSp.setHeadUrl(photo);
                            RongIM.getInstance().refreshUserInfoCache(new UserInfo(userID, nickName, Uri.parse(photo)));
                            RongIM.getInstance().setCurrentUserInfo(new UserInfo(userID, nickName, Uri.parse(photo)));
                        }
                    }
                }
            }.execute(path);
        } else {
            rivHeader.setBackgroundResource(R.drawable.de_default_portrait);
        }


    }
}
